package com.api.zszsj2.util;


import com.api.zszsj.sso.LogTool;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;


public class Signature {
    public static final LogTool logger = new LogTool("/log/dev/signature", false);
    /**
     * 利用java原生的摘要实现SHA256加密
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256SData(String str){
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (Exception e) {
            logger.writeLog(e.getMessage());
        }
        return encodeStr;
    }
    /**
     * 将byte转为16进制
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    /**
     * 将传入的密文转换为明文
     *@param data 密文字符串
     * @param pwd 密码
     * @return 解密后的明文
     */
    public static String decode(String data,String pwd) {
      String dataStr="";

        try {
            //byte[] iv = Base64.getDecoder().decode(data.substring(0, 24));
            byte[] encryptStr = Base64.getDecoder().decode(data);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
           // System.out.println(pwd);
            SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(StandardCharsets.UTF_8), "AES");
            //System.out.println(secretKey.getEncoded());
            cipher.init(2, secretKey);
            byte[] bytes = cipher.doFinal(encryptStr);
             dataStr = StringUtils.split(new String(bytes, StandardCharsets.UTF_8), "&")[1];


        } catch (Exception e) {
//            logger.writeLog("解密异常！"+e.getMessage());
            e.printStackTrace();
            return "";
        }

        return dataStr;
    }

    /**
     * 将传入的明文转换为密文
     * @param str 明文字符串
     * @param pwd 密码
     * @return 加密后的密文
     */
    public static String encode(String str,String pwd) {
      String result = "";
        try {
            String dataStr = RandomStringUtils.random(16, true, false) + "&" + str;
            logger.writeLog("加密前明文>>>"+dataStr);
            Cipher cipher = Cipher.getInstance(" AES/ECB/PKCS5Padding");
            SecretKeySpec secretKey = new SecretKeySpec(pwd.getBytes(StandardCharsets.UTF_8), "AES");
            cipher.init(1, secretKey);
            byte[] bytes = dataStr.getBytes(StandardCharsets.UTF_8);
            String ecnryptStr = Base64.getEncoder().encodeToString(cipher.doFinal(bytes));
            result=ecnryptStr;
        } catch (Exception e) {
            logger.writeLog("加密异常！"+e.getMessage());
            return null;
        }

        return  result;
    }

    /**
     * sha256_HMAC加密
     * @param message 消息
     * @param secret 秘钥
     * @return 加密后字符串
     */
    public static String getSignature(String message, String secret) {
        String hash = "";
        try {

            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(secretKey);
            String newSignature = Base64.getEncoder().encodeToString(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
            hash=newSignature;
        } catch (Exception e) {
            logger.writeLog("加密异常！"+e.getMessage());
        }

        return hash;

    }

    /**
     * 将加密后的字节数组转换成字符串
     * @param b 字节数组
     * @return 字符串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();

        String stmp;

        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);

            if (stmp.length() == 1)

                hs.append('0');

            hs.append(stmp);

        }
        return hs.toString().toLowerCase();
    }
}
